﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Tilemaps;

namespace Map
{
    public class MapApplier : MonoBehaviour
    {
        [Header("Obstacles")]
        [SerializeField] private Tilemap obstacleMap;
        [SerializeField] private TileBase obstacleTile;
        
        [Header("Resources")]
        [SerializeField] private Tilemap resourceMap;
        [SerializeField] private Transform[] resourcePrefabs;
        [SerializeField] private Transform starPrefab;
        
        
        private void Start()
        {
            if (MapGenerator.Map is null)
            {
                return;
            }
            
            obstacleMap.ClearAllTiles();
            foreach (Transform child in resourceMap.transform)
            {
                Destroy(child.gameObject);
            }

            PutMap(MapGenerator.Map);
        }

        private void PutMap(MapInfo map)
        {
            for (int x = 0; x < map.Height; x++)
            {
                for (int y = 0; y < map.Width; y++)
                {
                    Vector3Int tilePosition = map.GetTilePosition(x, y);
                    
                    switch (map.GetCellType(x, y))
                    {
                        case CellType.None:
                            break;
                        case CellType.Obstacle:
                            obstacleMap.SetTile(tilePosition, obstacleTile);
                            break;
                        case CellType.Path:
                            break;
                        case CellType.Resource:
                            if (!map.TryGetResourceID(x, y, out int resourceID))
                            {
                                Debug.LogError("Resource ID not found!");
                                return;
                            }

                            Vector3 worldPosition = resourceMap.GetCellCenterWorld(tilePosition);
                            Transform resource = Instantiate(resourcePrefabs[resourceID], worldPosition, Quaternion.identity);
                            resource.SetParent(resourceMap.transform);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
            }
            
            Vector3 destinationWorldPosition = resourceMap.GetCellCenterWorld(new Vector3Int(map.Destination.x, map.Destination.y));
            Transform star = Instantiate(starPrefab, destinationWorldPosition, Quaternion.identity);
            star.SetParent(resourceMap.transform);
        }
    }
}